﻿using System;
using System.Collections.ObjectModel;
using GeoAPI.Geometries;
using NetTopologySuite.CoordinateSystems;

namespace NetTopologySuite.Features
{
	[Serializable]
	public class FeatureCollection
	{
		public Collection<IFeature> Features { get; private set; }

		public string Type { get; private set; }

		public ICRSObject CRS { get; set; }

		public IFeature this[int index]
		{
			get
			{
				return this.Features[index];
			}
		}

		public int Count
		{
			get
			{
				return this.Features.Count;
			}
		}

		public FeatureCollection(Collection<IFeature> features)
		{
			this.Type = "FeatureCollection";
			this.Features = (features ?? new Collection<IFeature>());
		}

		public FeatureCollection() : this(null)
		{
		}

		public void Add(IFeature feature)
		{
			this.Features.Add(feature);
		}

		public bool Remove(IFeature feature)
		{
			return this.Features.Remove(feature);
		}

		public void RemoveAt(int index)
		{
			this.Features.RemoveAt(index);
		}

		public Envelope BoundingBox
		{
			get
			{
				if (this._boundingBox == null)
				{
					this._boundingBox = this.ComputeBoundingBox();
				}
				if (this._boundingBox != null)
				{
					return new Envelope(this._boundingBox);
				}
				return null;
			}
			set
			{
				this._boundingBox = value;
			}
		}

		private Envelope ComputeBoundingBox()
		{
			if (!Feature.ComputeBoundingBoxWhenItIsMissing)
			{
				return null;
			}
			Envelope envelope = new Envelope();
			foreach (IFeature feature in this.Features)
			{
				if (feature.BoundingBox != null)
				{
					envelope.ExpandToInclude(feature.BoundingBox);
				}
				else if (feature.Geometry != null)
				{
					envelope.ExpandToInclude(feature.Geometry.EnvelopeInternal);
				}
			}
			return envelope;
		}

		private Envelope _boundingBox;
	}
}
